package com.zhang.authoritycenter.security;

import com.alibaba.fastjson.JSON;
import com.zhang.infrastructure.model.KingHoodResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class JwtAccessDeniedHandler implements AccessDeniedHandler {

   @Override
   public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
      // 这是调用当用户试图访问一个安全的REST资源没有必要的授权，我们应该只是发送一个403禁止的响应，
      // 因为没有 '错误' 页面重定向到这里你可以把你想要的任何消息
//      response.sendError(HttpServletResponse.SC_FORBIDDEN, accessDeniedException.getMessage());

      log.error("需要token的资源，请求没有token，{}",accessDeniedException.getMessage());
      response.setContentType("application/json;charset=utf-8");
      KingHoodResponseVO<Object> kingHoodResponseVO = KingHoodResponseVO.fail(HttpServletResponse.SC_FORBIDDEN, "没有携带token");
      response.getWriter().println(JSON.toJSONString(kingHoodResponseVO));
      response.getWriter().flush();
   }
}
